home *** CD-ROM | disk | FTP | other *** search
- Path: columba.udac.uu.se!news
- From: Enrico Savazzi <enrico.savazzi@pal.uu.se>
- Newsgroups: comp.lang.c++
- Subject: Re: new and 2-D Arrays?
- Date: Thu, 08 Feb 1996 16:55:37 +0100
- Organization: Uppsala University
- Message-ID: <311A1CF9.5D84@pal.uu.se>
- References: <4famh5$chp@canyon.sr.hp.com> <4fatc0$8lg@cloner4.netcom.com>
- NNTP-Posting-Host: esavazzi.pal.uu.se
- Mime-Version: 1.0
- Content-Type: text/plain; charset=us-ascii
- Content-Transfer-Encoding: 7bit
- X-Mailer: Mozilla 2.0 (WinNT; I)
-
- Michael Judge wrote:
- >
- > In <4famh5$chp@canyon.sr.hp.com> rolando@sr.hp.com (Rolando Ampuero)
- > writes:
- > >
- > >Hello, This question was problably asked already, but as a newbie in
- > the
- > >world of C++, this is one place I found that relates to this subject.
- > >According to several manuals that I have read I can declare a two
- > dimensional
- > >array in this manner
- > >
- > >int *myptr = new int [8][8];
- > >
- > >but when I tried to compile I get errors, is this not the correct way
- > to do
- > >it? Are the books wrong? (One of the books is Deitel pg 415).I passed through the same stage, and found an answer by accident only much later.
- I do not know of any compiler that will accept your solution. If you know the size
- of the array at compile time, then declare it statically:
- int a[8][8];
-
- otherwise, use new. However, keep in mind that a two-dimensional array requires a
- pointer to an array of pointers to arrays. Therefore:
- int** a; // not just int*
- a = new int* [m];
- for (int i = 0; i < m; i++)
- a[i] = new int [n];
- // use the array a[m][n] here
- for (i = 0; i < m; i++)
- delete [] a[i];
- delete a;
-
- Note that you must delete in reverse order, or the code will bomb. If you need
- three or more dimensions, nest more loops. Keep in mind, however, that
- uni-dimensional arrays are faster to access than multi-dimensional ones. If you
- want speed, use a uni-dimensional array and do the pointer arithmetics explicitly.
- Another big difference between uni- and multi-dimensional arrays is that uni's are
- contiguous in memory, while multi's need not to be. Multi's also require more
- memory to store the arrays of pointers.
-